﻿<%@ WebHandler Language="C#" Class="Upload" %>

using System;
using System.Web;
using System.IO;
using ORM;
using static Constants;

/// <summary>
/// </summary>
public class Upload : IHttpHandler
{
	public bool IsReusable => false;

	public void ProcessRequest(HttpContext context)
	{
		HttpRequest request = context.Request;

		if (request.Files.Count == 0) return;

		string uploadName = request.Files.Keys[0], subdir = request.Form["subdir"] ?? "";
		string filename;
		if (string.IsNullOrEmpty(context.Request.Form["append"]))
		{
			var dir = context.Server.MapPath(Path.Combine("/attachment", subdir));
			Directory.CreateDirectory(dir);
			filename = Path.Combine(dir, "{0}.{1}".Fmt(Helper.NewId.ToString("x"), uploadName));

			Uploadings[relativePath(filename)] = DateTime.Now;
		}
		else
			filename = context.Request.Form["append"];

		if (filename.StartsWith("/")) filename = context.Server.MapPath(filename);
		var dest = new FileStream(filename, FileMode.Append);
		request.Files[0].InputStream.CopyTo(dest);
		dest.Close();

		context.Response.ContentType = "text/plain";
		context.Response.Write("{0}|{1}".Fmt(uploadName, relativePath(filename)));
	}

	string relativePath(string filename) => filename.Replace(HttpContext.Current.Server.MapPath("/"), "/").Replace("\\", "/");
}